//
//  ViewController.m
//  Test
//
//  Created by tanqilong on 16/7/1.
//  Copyright © 2016年 tanqilong. All rights reserved.
//

#import "ViewController.h"

char * t = "5abcae";

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    int a[10] = {1,2,3,5,9,10,11,14,15,16};
    int index = [self finde:a count:10 Key:11];
    if (index != -1) {
        NSLog(@"位置%d",index);
    } else {
        NSLog(@"没有找到");
    }
}

//二分查找
-(int)finde:(int[])array count:(int)count Key:(int)key {
    int low = 0,height = count -1;
    BOOL isFind = NO; int mid = -1;
    int findCount = 0;
    while (low <= height && !isFind) {
        mid =  (low + height) / 2;
        if (key < array[mid]) {
            height -= 1;
        }
        else if (key > array[mid]) {
            low+=1;
        } else {
            isFind = YES;
        }
        findCount ++;
    }
    NSLog(@"查找次数%d",findCount);
    
    if (isFind) {
        return mid;
    } else {
        return -1;
    }
}


@end
